﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Services;
using XHD.Common;
using XHD.DBUtility;
using XHD.Model;

namespace XHD.View.WebService
{
    /// <summary>
    /// AppApi 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
     [System.Web.Script.Services.ScriptService]
    public class AppApi : System.Web.Services.WebService
    {
         

        /// <summary>
        /// 登录Token预留小程序
        /// </summary>
        /// <param name="JsonParam">{url:'',ClientId:'',uid:'',pwd:'',Token:''}</param>
        [WebMethod]
        public void Login(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {
                     
                    var r = AppApiSQL.Login(jcode["url"].ToString()
                        , jcode["ClientId"].ToString()
                        , jcode["uid"].ToString()
                        , jcode["pwd"].ToString()
                         , jcode["Token"].ToString());
                    if (r.Item2 == "")
                    {
                         
                         data = r.Item1.Tables[0]; errcode = 0;  
                    }
                    else
                    {
                        errmsg = r.Item2;
                    }

                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data = data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }
        /// <summary>
        /// 小程序
        /// </summary>
        /// <param name="JsonParam"></param>
        [WebMethod]
        public void LoginSmall(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {

                    var r = AppApiSQL.LoginSmall(jcode["openid"].ToString()
                        , jcode["ClientId"].ToString()
                        , jcode["url"].ToString());
                    if (r.Item2 == "")
                    {

                        data = r.Item1.Tables[0]; errcode = 0;
                    }
                    else
                    {
                        errmsg = r.Item2;
                    }

                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data = data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }


        [WebMethod]
        public void GetOpenId(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {
                    string AppID = PubConstant.GetConnectionString("AppID");
                    string AppSecret = PubConstant.GetConnectionString("AppSecret");
                    Common.WebClient wc = new Common.WebClient();
                    string url = "  https://api.weixin.qq.com/sns/jscode2session?appid="+ AppID + "&secret="+ AppSecret + "&js_code="+ jcode["code"].ToString() + "&grant_type=authorization_code";
                    var r= wc.GetHtml(url);

                    if (r.Contains("openid")) errcode = 0;
                    data = r; 
                  

                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }


            object o = new
            {
                code = errcode,
                msg = errmsg,
                data = data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="JsonParam"></param>
        [WebMethod]
        public void SmallReg_Data(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {

                    var r = AppApiSQL.SmallReg_Data(jcode["WX_ID"].ToString(), jcode["WX_Name"].ToString()
                        , jcode["tel"].ToString()
                        , jcode["type"].ToString(), jcode["uid"].ToString());
                    if (r.Item2 == "")
                    {

                        data = r.Item1.Tables[0]; errcode = 0;
                    }
                    else
                    {
                        errmsg = r.Item2;
                    }

                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data = data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }

        [WebMethod]
        public void UpdateCusData(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {

                    int r = AppApiSQL.updateCusData(jcode["WX_ID"].ToString(), jcode["Content"].ToString()
                        , jcode["tel"].ToString()
                        , jcode["type"].ToString());
                    if (r>0)
                    {

                        errcode = 0;
                    }
                     

                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data = data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="JsonParam"></param>
        [WebMethod]
        public void HomeData(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {

                    var r = AppApiSQL.HomeData(jcode["uid"].ToString()
                        , jcode["ctype"].ToString()
                        , jcode["type"].ToString());
                    if (r.Item2 == "")
                    {

                        data = r.Item1; errcode = 0;
                    }
                    else
                    {
                        errmsg = r.Item2;
                    }

                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data = data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }


        [WebMethod]
        public void HomeData2(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {
                    if (jcode["type"].ToString() == "Para")
                    {

                        var r = AppApiSQL.HomeData2Para();
                        if (r.Item2 == "")
                        {

                            data = r.Item1; errcode = 0;
                        }
                        else
                        {
                            errmsg = r.Item2;
                        }
                    }
                    else if (jcode["type"].ToString() == "Home")
                    {
                        var r = AppApiSQL.HomeData2(jcode["category_name"].ToString()
                            , jcode["keyword"].ToString(), jcode["Top"].ToString());
                        if (r.Item2 == "")
                        {

                            data = r.Item1; errcode = 0;
                        }
                        else
                        {
                            errmsg = r.Item2;
                        }
                    }
                    else if (jcode["type"].ToString() == "News")
                    {
                        var r = AppApiSQL.GetDataNews(jcode["newtype"].ToString()
                            , jcode["top"].ToString());
                        if (r.Item2 == "")
                        {

                            data = r.Item1; errcode = 0;
                        }
                        else
                        {
                            errmsg = r.Item2;
                        }
                    }
                    else if (jcode["type"].ToString() == "HomeDetail")
                    {
                        var r = AppApiSQL.HomeDataDetail2(jcode["category_name"].ToString()
                            , jcode["keyword"].ToString());
                        if (r.Item2 == "")
                        {

                            data = r.Item1; errcode = 0;
                        }
                        else
                        {
                            errmsg = r.Item2;
                        }
                    }

                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data = data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }
        /// <summary>
        /// 订单信息
        /// </summary>
        /// <param name="JsonParam"></param>
        [WebMethod]
        public void OrderData(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {
                    if (jcode["type"].ToString() == "List") {
                        var r = AppApiSQL.SaleOrderList(jcode["uid"].ToString()
                        , jcode["ctype"].ToString(), jcode["pageIndex"].ToString(), jcode["pageSize"].ToString());
                        if (r.Item2 == "")
                        { 
                            data = r.Item1.Tables[0]; errcode = 0;
                        }
                        else
                        {
                            errmsg = r.Item2;
                        }
                    } 
                    else if (jcode["type"].ToString() == "Detail") {
                        var rx = AppApiSQL.SaleOrderDetail(jcode["id"].ToString());
                        if (rx.Item2 == "")
                        {

                            data = rx.Item1; errcode = 0;
                        }
                        else
                        {
                            errmsg = rx.Item2;
                        }
                    }
                   

                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data = data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }



        [WebMethod]
        public void UpdateCollectionOrder(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {

                    var r = AppApiSQL.UpdateCollectionOrder(jcode["CId"].ToString(), jcode["uid"].ToString());
                    if (r.Item2 == "")
                    {
                          errcode = 0;
                    }
                    else
                    {
                        errmsg = r.Item2;
                    }

                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg 
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }


        #region APP接口
        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="JsonParam"></param>

        [WebMethod]
        public void GetBoardDetailData(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {

                    var r = AppApiSQL.GetBoardDetailData(jcode["barcode"].ToString());
                    if (r.Item2 == "")
                    {

                        data = r.Item1.Tables[0]; errcode = 0;
                    }
                    else
                    {
                        errmsg = r.Item2;
                    }

                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data = data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }

        /// <summary>
        /// 待采/已采/明日
        /// </summary>
        /// <param name="JsonParam"></param>
        [WebMethod]
        public void CollectionOrderList(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {

                    var r = AppApiSQL.ColloctionOrderList(jcode["status"].ToString(),  jcode["bid"].ToString(), jcode["startdate"].ToString(), jcode["enddate"].ToString());
                    if (r.Item2 == "")
                    {
                        errcode = 0;
                        data = r.Item1;
                    }
                    else
                    {
                        errmsg = r.Item2;
                    }

                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data = data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }

        /// <summary>
        /// 巡查
        /// </summary>
        /// <param name="JsonParam"></param>
        [WebMethod]
        public void InsertBasic_Boar_Heath(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                Basic_Boar_Heath jcode = AppApiUtils.Deserialize<Basic_Boar_Heath>(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {
                    BLL.Basic_Boar_Heath bll = new BLL.Basic_Boar_Heath();
                    bool r = bll.Add(jcode);
                    if (r)
                    {
                        errcode = 0;
                    }
                    else
                    {
                        errmsg = "插入失败";
                    }

                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }

        /// <summary>
        /// 巡查列表{"boarId":""}
        /// </summary>
        /// <param name="JsonParam"></param>
        [WebMethod]
        public void Basic_Boar_HeathList(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {
                    BLL.Basic_Boar_Heath bll = new BLL.Basic_Boar_Heath();
                    string strWhere = "1=1";
                    if (jcode["boarId"].ToString()!="")//ID
                    strWhere += " AND boarId='"+ jcode["boarId"].ToString() + "'";
                    if (jcode["enddate"].ToString() != "")//结束时间
                        strWhere += " AND monitorDate<='" + jcode["enddate"].ToString() + "'";
                    if (jcode["startdate"].ToString() != "")//开始时间
                        strWhere += " AND monitorDate>='" + jcode["startdate"].ToString() + "'";
                    if (jcode["temperature"].ToString() != "")//体温
                        strWhere += " AND temperature>='" + jcode["temperature"].ToString() + "'";
                    var r = bll.GetList(strWhere);
                    if (r.Tables.Count>0)
                    {
                        errcode = 0;
                        data=r;
                    }
                    else
                    {
                        errmsg = "无信息";
                    }

                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data=data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }
        /// <summary>
        /// 畜舍/栏列表  type dornId
        /// </summary>
        /// <param name="JsonParam"></param>

        [WebMethod]
        public void Dorm_CorralList(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {
                    if (jcode["type"].ToString() == "Dorm")
                    {
                        BLL.Basic_dorm bll = new BLL.Basic_dorm();

                        var r = bll.GetAllList();
                        if (r.Tables.Count > 0)
                        {
                            errcode = 0;
                            data = r;
                        }
                        else
                        {
                            errmsg = "无信息";
                        }
                    }
                    else if (jcode["type"].ToString() == "Corral")
                    {

                        BLL.Basic_corral bll = new BLL.Basic_corral();
                        string strWhere = "1=1";
                        strWhere += " AND dornId='" + jcode["dornId"].ToString() + "'";
                        var r = bll.GetList(strWhere);
                        if (r.Tables.Count > 0)
                        {
                            errcode = 0;
                            data = r;
                        }
                        else
                        {
                            errmsg = "无信息";
                        }
                    }
                    else if (jcode["type"].ToString() == "Log")
                    {

                        BLL.Basic_corral bll = new BLL.Basic_corral();
                        string strWhere = "1=1";
                        if(jcode["dornId"].ToString()!="")
                        strWhere += " AND dornId='" + jcode["dornId"].ToString() + "'";
                        if (jcode["corralId"].ToString() != "")
                            strWhere += " AND corralId='" + jcode["corralId"].ToString() + "'";
                        //if (jcode["startdate"].ToString() != "")
                        //    strWhere += " AND createTime>='" + jcode["startdate"].ToString() + "'";
                        //if (jcode["enddate"].ToString() != "")
                        //    strWhere += " AND createTime<='" + jcode["enddate"].ToString() + "'";
                        string  Total = "";
                        var r = bll.GetListLog(999, 1, strWhere, " id desc", out Total);
                        if (r.Tables.Count > 0)
                        {
                            errcode = 0;
                            data = r;
                        }
                        else
                        {
                            errmsg = "无信息";
                        }
                    }

                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data=data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }

        /// <summary>
        /// 验证畜舍/栏是否有种禽
        /// </summary>
        /// <param name="JsonParam"></param>
        [WebMethod]
        public void ChangeCheck(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {
                     
                        var r = AppApiSQL.ChangeCheck(jcode["dornId"].ToString(), jcode["corralId"].ToString());
                        if (r=="")
                        {
                            errcode = 0; 
                        }
                        else
                        {
                            errmsg = r;
                        }
                    

                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }
        [WebMethod]
        public void ChangeLogList(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {

                    var r = AppApiSQL.changeLog(jcode["bid"].ToString(),jcode["dornId"].ToString(), jcode["corralId"].ToString(), jcode["startdate"].ToString(), jcode["enddate"].ToString());
                    if (r.Item2 == "")
                    {
                        errcode = 0;
                        data = r.Item1;
                    }
                    else
                    {
                        errmsg = r.Item2;
                    }


                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data=data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }
        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="JsonParam"></param>
        [WebMethod]
        public void ChangeSave(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {

                    var r = AppApiSQL.saveChange(jcode["type"].ToString(), jcode["BoarId"].ToString(),
                        jcode["dornId"].ToString(), jcode["corralId"].ToString(),
                        jcode["emp_name"].ToString(), jcode["IsDirect"].ToString());
                    if (r == "")
                    {
                        errcode = 0;
                    }
                    else
                    {
                        errmsg = r;
                    }


                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }

        [WebMethod]
        public void GetSysInfo()
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
               
                    string sql = "SELECT * FROM  dbo.Sys_info";
                    var r = DbHelperSQL.Query(sql);
                    if (r.Tables[0].Rows.Count>=0)
                    {
                        errcode = 0;
                        data = r;
                    }
                    else
                    {
                        errmsg = "获取失败";
                    }


               
            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data = data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }

        [WebMethod]
        public void GetOrderInfo(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {
                  
                    BLL.Sale_order order = new BLL.Sale_order();
                    BLL.Sale_order_details detail = new BLL.Sale_order_details();
                    DataSet ds1 = order.GetList(" Sale_order.Serialnumber='" + jcode["OrderId"].ToString() + "'");
                    if (ds1.Tables[0].Rows.Count > 0) {
                        DataSet ds2 = detail.GetList(" order_id='"+ds1.Tables[0].Rows[0]["id"].ToString()+"' ");

                        object obj = new
                        {
                            HeadData = ds1.Tables[0],
                            DetailData = ds2.Tables[0]
                        };
                        data = obj;
                        errcode = 0; errmsg = "success";
                    }
                    
                    

                }
               


            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data = data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }

        [WebMethod]
        public void GetOrderList(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {

                    BLL.Sale_order order = new BLL.Sale_order();
                    BLL.Sale_order_details detail = new BLL.Sale_order_details();
                    //订单号，时间，客户
                    string keyword = "", strWhere = " 1=1"; ;
                    if (jcode["OrderId"].ToString() != "") {

                        strWhere += " AND Sale_order.[Serialnumber] LIKE '%"+ jcode["OrderId"].ToString()+"%'";
                    }
                    if (jcode["Order_date_B"].ToString() != "")
                    {

                        strWhere += " AND Sale_order.[Order_date] >= '" + jcode["Order_date_B"].ToString() + "'";
                    }
                    if (jcode["Order_date_E"].ToString() != "")
                    {

                        strWhere += " AND Sale_order.[Order_date] <= '" + jcode["Order_date_E"].ToString() + "'";
                    }
                    if (jcode["cus_name"].ToString() != "")
                    {

                        strWhere += " AND CRM_Customer.[cus_name] LIKE '%" + jcode["cus_name"].ToString() + "%'";
                    }
                    DataSet ds1 = order.GetList(strWhere);
                     data = ds1; errcode = 0; errmsg = "success";
                }
 

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data = data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }



        [WebMethod]
        public void SaveSmallOrderData(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {
                    BLL.SmallAPP_Order_Head h = new BLL.SmallAPP_Order_Head();
                    BLL.smallApp_Order_Body b = new BLL.smallApp_Order_Body();

                    //Model.smallApp_Order_Body bModel = new smallApp_Order_Body();
                    //  Model.SmallAPP_Order_Head hModel = new SmallAPP_Order_Head();
                    //0 购物车   1待付款，2已付款，3备货中，Y已发货
                    if (jcode["type"].ToString() == "Insert")
                    {
                        BLL.Sys_Param sp = new BLL.Sys_Param();
                        string OrderID = sp.GetBarCode("SMALLORDER"); ;
                        bool IsExistOrderID = false;
                        bool boolh = true; bool boolb = true;
                        if (jcode["IsBuyCar"].ToString() == "Y") OrderID = "BuyCar" + jcode["WX_ID"].ToString();
                        Model.SmallAPP_Order_Head hModel = Common.DataToJson.Deserialize<SmallAPP_Order_Head>(jcode["headData"].ToString());
                        List<smallApp_Order_Body> bModels = Common.DataToJson.Deserialize<List<smallApp_Order_Body>>(jcode["bodyData"].ToString());
                        hModel.OrderId = OrderID;
                        hModel.CreateTime = DateTime.Now;
                        if (h.Exists(OrderID)) IsExistOrderID = true;
                        if (!IsExistOrderID)
                            boolh = h.Add(hModel);

                        foreach (smallApp_Order_Body bModel in bModels)
                        {
                            if (bModel == null) return;
                            if (jcode["IsBuyCar"].ToString() == "N-Car")//购物车转换为正式订单
                            {
                                string d_OrderId = "BuyCar" + jcode["WX_ID"].ToString();
                                b.Delete(d_OrderId, bModel.ProductId);
                            }
                            bool bb = false;
                            bModel.OrderId = OrderID;
                            if (b.Exists(OrderID, bModel.ProductId))
                                bb = b.Update(bModel);
                            else
                                bb = b.Add(bModel);
                            if (!bb)
                                boolb = false;
                        }


                        if (boolh && boolb)
                        {
                            errcode = 0;errmsg = OrderID;
                        }
                        else
                        {
                            errmsg = "单据保存错误!";
                        }
                    }
                    else if (jcode["type"].ToString() == "Del")
                    {
                        string d_OrderId = "BuyCar" + jcode["WX_ID"].ToString();
                      bool delb=  b.Delete(d_OrderId, jcode["ProductId"].ToString());
                        if (delb) { errcode = 0; }
                    }
                    else if (jcode["type"].ToString() == "Update")
                    {
                        Model.SmallAPP_Order_Head hModel = Common.DataToJson.Deserialize<SmallAPP_Order_Head>(jcode["headData"].ToString());
                        List<smallApp_Order_Body> bModels = Common.DataToJson.Deserialize<List<smallApp_Order_Body>>(jcode["bodyData"].ToString());
                        hModel.CreateTime = DateTime.Now;
                        bool boolh = h.Update(hModel);
                        bool boolb = true;
                        foreach (smallApp_Order_Body bModel in bModels)
                        {
                            bool bb = b.Update(bModel);
                            if (!bb)
                                boolb = false;
                        }

                        if (boolh && boolb)
                        {
                            errcode = 0;
                        }
                        else
                        {
                            errmsg = "单据保存错误!";
                        }
                    }
                   
                    else if (jcode["type"].ToString() == "List")
                    {
                        string strWhere = " 1=1";
                        if (jcode["WX_ID"].ToString() != "")
                        {
                            strWhere += " AND WX_ID='" + jcode["WX_ID"].ToString() + "'";
                        }
                        if (jcode["IsBuyCar"].ToString() == "Y") strWhere += " OrderID = 'BuyCar";
                        int pIndex = int.Parse(jcode["pageIndex"].ToString());
                        int pSize = int.Parse(jcode["pageSize"].ToString());
                        DataSet ds = h.GetListByPage(strWhere, "CreateTime", (pIndex - 1) * pSize, pIndex * pSize);
                        errcode = 0; data = ds;
                    }
                    else if (jcode["type"].ToString() == "ListDetail")
                    {
                        var r = AppApiSQL.smallDataListDetail(jcode["WX_ID"].ToString(), jcode["status"].ToString(), int.Parse(jcode["pageIndex"].ToString()));
                        if (r.Item2 == "")
                        {

                            data = r.Item1;
                            if (r.Item1.Count == 0)
                            {
                                errmsg = "nomore";
                            }
                            else errcode = 0;

                        }
                        else
                            errmsg = r.Item2;
                    }
                    else if (jcode["type"].ToString() == "Detail")
                    {
                        string imgurl = PubConstant.GetConnectionString("smallAppImgUrl");
                        StringBuilder sb = new StringBuilder();
                        sb.AppendLine(" SELECT  *,'" + imgurl + "Images/upload/product/" + "'+img as headimg FROM  dbo.smallApp_Order_Body A  ");
                        sb.AppendLine(" INNER JOIN dbo.SmallAPP_Order_Head B ON	 B.OrderId = A.OrderId  ");
                        sb.AppendLine(" INNER JOIN  dbo.Product C ON A.ProductId=C.id  ");
                        sb.AppendLine(" WHERE	 B.WX_ID='" + jcode["WX_ID"].ToString() + "' AND	 A.OrderId='" + jcode["OrderId"].ToString() + "'  ");

                        sb.AppendLine("  SELECT * FROM dbo.CRM_Customer_Address WHERE Id IN(SELECT addressId FROM  dbo.SmallAPP_Order_Head WHERE	  WX_ID='" + jcode["WX_ID"].ToString() + "' AND	  OrderId='" + jcode["OrderId"].ToString() + "'   )");
                      
                        DataSet ds = DbHelperSQL.Query(sb.ToString());
                        errcode = 0; data = ds;
                    }

                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data = data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }

        [WebMethod]
        public void SaveSmallCusAddress(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {
                    BLL.CRM_Customer_Address bll= new BLL.CRM_Customer_Address(); 

                
                    //  Model.SmallAPP_Order_Head hModel = new SmallAPP_Order_Head();
                    //0 购物车   1待付款，2已付款，3备货中，Y已发货
                    if (jcode["type"].ToString() == "Insert")
                    {
                      
                        Model.CRM_Customer_Address Model = Common.DataToJson.Deserialize<CRM_Customer_Address>(jcode["Data"].ToString());
                        Model.Id = Guid.NewGuid().ToString();
                        Model.CreatTime = DateTime.Now;

                        bool b = bll.Add(Model);
 
                        if (b)
                        {
                            errcode = 0;  
                        }
                        else
                        {
                            errmsg = "单据保存错误!";
                        }
                    }
                    else if (jcode["type"].ToString() == "Del")
                    {
                        string id    = jcode["id"].ToString();
                        bool delb = bll.Delete(id);
                        if (delb) { errcode = 0; }
                    }
                    else if (jcode["type"].ToString() == "Update")
                    {
                        Model.CRM_Customer_Address Model = Common.DataToJson.Deserialize<CRM_Customer_Address>(jcode["Data"].ToString());
                         Model.CreatTime = DateTime.Now;
                        bool boolh = bll.Update(Model); 
                        

                        if (boolh)
                        {
                            errcode = 0;
                        }
                        else
                        {
                            errmsg = "单据保存错误!";
                        }
                    }

                    else if (jcode["type"].ToString() == "List")
                    {
                        string strWhere = " 1=1";
                        if (jcode["WX_ID"].ToString() != "")
                        {
                            strWhere += " AND CusId='" + jcode["WX_ID"].ToString() + "'";
                        }
                      
                        int pIndex = int.Parse(jcode["pageIndex"].ToString());
                        int pSize = int.Parse(jcode["pageSize"].ToString());
                        DataSet ds = bll.GetListByPage(strWhere, "CreatTime", (pIndex - 1) * pSize, pIndex * pSize);
                        errcode = 0; data = ds;
                    }
               
                    else if (jcode["type"].ToString() == "Detail")
                    {
                          StringBuilder sb = new StringBuilder();
                        sb.AppendLine(" SELECT  *  FROM  dbo.CRM_Customer_Address A  "); 
                        sb.AppendLine(" WHERE	  CusId='" + jcode["WX_ID"].ToString() + "' AND	 id='" + jcode["id"].ToString() + "'  ");
                        DataSet ds = DbHelperSQL.Query(sb.ToString());
                        errcode = 0; data = ds;
                    }

                }

            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data = data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }

        #endregion

        [WebMethod]
        public void testpostfile()
        {
            int errcode = -1; string errmsg = "faile";
            object data = null;
            try
            {
                string url = "http://api.humuyun.com/api/ShXxSperm";
                string filePath = @"C:\Users\huazha01\OneDrive\图片\alarmtimes.png";
                string appkey = "7492D92B81024810D757D87A4702BF01";
                string deviceId = "MYJCN1D009Y17";
                string strdata = "[{\"vbatch\":\"LOT20240221001\",\"tcheckoutDate\":\"2024-02-21\",\"vcheckoutTime\":\"10:12\",\"voperator\":\"张三\",\"wtype\":\"鲜精\",\"ddensity\":213.48,\"dvitality\":94.55,\"icopies\":12,\"dadd\":632,\"vresult\":\"757\",\"dcapacity\":60,\"dmilliliter\":125,\"dmotileSperms\":2000,\"dmalformation\":2115.06,\"bstandard\":true,\"vfile\":[{\"vtpmc\":\"DD1234-C1-1\",\"vfile\":\"category-a.png\"}],\"mxlist\":[{\"vgzgP\":\"DD1234\",\"tcsrq\":\"2021-01-02\",\"vpz\":\"DD\",\"vpx\":\"美系\"}]}]";
                string postfile = HttpUtility.UrlEncode("file=" + filePath + "&appkey=" + appkey + "&deviceId=" + deviceId + "&data=" + strdata);
                NameValueCollection nvc1 = new NameValueCollection();
                nvc1.Add("appkey", "7492D92B81024810D757D87A4702BF01");
                nvc1.Add("deviceId", "MYJCN1D009Y17");
                nvc1.Add("data", strdata);
                NameValueCollection nvcfile = new NameValueCollection();
                nvcfile.Add("file", filePath);
                var head = new Dictionary<string, string>
                                {
                                { "Method", "POST" },
                                { "ContentType", "application/x-www-form-urlencoded; charset=UTF-8" }
                                };
                string rest = comm.PostMultipartFormData(url, head, nvc1, nvcfile);
                errmsg = rest;
            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data = data
            };

            ReturnStr(AppApiUtils.ToJson(o));

        }




        public void OK(string JsonParam)
        {
            int errcode = -1; string errmsg = "faile";
            object data = null; string count = "0";
            try
            {
                JObject jcode = AppApiUtils.DataToJObject(JsonParam);
                if (jcode == null) errmsg = "参数传入错误！";
                else
                {

                }
            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
            }

            object o = new
            {
                code = errcode,
                msg = errmsg,
                data = data,
                Total = count
            };


            ReturnStr(AppApiUtils.ToJson(o));
        }

        protected virtual void Success(string message)
        {
            ReturnStr(new ActionResult { type =  ResultType.success, message = message }.ToJson());
        }
        protected virtual void Success(string message, object data)
        {
            ReturnStr(new ActionResult { type = ResultType.success, message = message, result = data }.ToJson());
        }
        protected virtual void Error(string message)
        {
            ReturnStr(new   ActionResult { type =  ResultType.error, message = message }.ToJson());
        }

        private void ReturnStr(object o)
        {
            Context.Response.Charset = "utf-8"; //设置字符集类型  
            Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            Context.Response.Write(o);
            Context.Response.End();
        }



        private string RichTextParse(string text)
        {
            string re_text;
            // 替换包着img标签的figure标签，改为能被uniapp理解的div
            re_text = text.Replace("<figure/gi", "<div");

            re_text = text.Replace("</figure>/gi", " </div>");
            // 为p添加内边距，尽量达到与Web端的预览相同
            re_text = text.Replace("< p / gi", "<p style=\"padding: 10px 0px;\"");
            //  为字体附上颜色
            re_text = text.Replace("< font color =/ gi", "<font style=\"color: ");
             // 删除空的style属性，避免因为和已有的style属性冲突导致不显示
            re_text = text.Replace("style = /gi", "") ;
            return re_text;
        }
        public string Decode(string str)

        {

            str = str.Replace("<br/>", "\n");

            str = str.Replace("<br>", "\n");

            str = str.Replace("&gt", ">");

            str = str.Replace("&lt", "<");

            str = str.Replace("&nbsp;", " ");

            str = str.Replace("&quot;", "\"");

            str = str.Replace("''", "'");

            str = str.Replace("&amp", "&");

            return str;

        }

    }
}
